<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-form ref="formRef" :model="formInfo" inline size="small" label-width="100" class="form_class" :rules="rules">
    <el-form-item label="配置方式:" prop="configMethod">
      <el-radio-group v-model="formInfo.configMethod" @change="configMethodChange">
        <el-radio :value="1" size="small">从数据模板中选择</el-radio>
        <el-radio :value="2" size="small">自定义配置</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="业务场景:" prop="businessId">
      <el-select style="width: 100%;" v-model="formInfo.businessId" clearable @change="businessSceneChange">
        <el-option v-for="item in businessSceneList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="要素库类型:" prop="databaseType">
      <el-select style="width: 100%;" v-model="formInfo.databaseType" clearable @change="databaseChange">
        <el-option v-for="item in metadataLibrarys" :key="item.id" :label="item.name" :value="item.name"></el-option>
      </el-select>
    </el-form-item>
    <template v-if="formInfo.configMethod == '2'">
      <el-form-item label="数据库表:" prop="tableName">
        <el-select style="width: 100%;" v-model="formInfo.tableName" clearable @change="tableChange">
          <el-option v-for="(item, index) in tableList" :key="index" :label="item.tableName" :value="item.tableName"></el-option>
        </el-select>
      </el-form-item>
    </template>
    <template v-else-if="formInfo.configMethod == '1'">
      <el-form-item label="模板名称:" prop="templateId">
        <el-select style="width: calc(100% - 130px);" v-model="formInfo.templateId" clearable @change="moduleChange">
          <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id"></el-option>
        </el-select>
        <el-button style="width: 120px; margin-left: 10px;" size="small" @click="addTemplate">新增模板</el-button>
      </el-form-item>
    </template>
    <el-form-item label="字段映射:">
      <el-table :data="formInfo.mapFields" border>
        <el-table-column label="源表字段" align="center" prop="sourceField" width="200">
          <template #default="scope">
            <el-select v-model="scope.row.sourceField" placeholder="请选择源表字段" @change="fieldChange($event, scope.$index)">
              <el-option :disabled="curSourceFields.indexOf(item.fieldName) > -1" v-for="item in props.sourceTable" :key="item.fieldName" :label="item.fieldName" :value="item.fieldName"></el-option>
            </el-select>
          </template> 
        </el-table-column>
        <el-table-column label="目标字段" align="center" prop="targetField" />
        <el-table-column label="字段类型" align="center" prop="targetFieldType" />
      </el-table>
    </el-form-item>
  </el-form>
  <AddTemplate :addVisible="addVisible" :type="addType" :rowData="currentData" v-if="addVisible" @handleEvent="handleEvent" />
</template>
        
<script name="TaskTargetConfig" setup>
import AddTemplate from '../../dataTemplate/component/AddTemplate.vue';
import { getBusinessSceneDefinitionList, getMetadataDatabaseListByBusinessSceneCode, getMetadataTableInfo } from '@/api/metaData';
import { getTemplateByCondition, getDataSourceDetail } from '@/api/dataIntegration/dataSync';
const props = defineProps(['formInfo', 'sourceTable']);
const formRef = ref();
const addVisible = ref(false);
const addType = ref('add');
const currentData = ref(null);
// const sourceTaleList = ref([]); // 源表字段列表
const formInfo = ref({
  configMethod: '',
  businessId: '',
  databaseType: '',
  templateId: '',
  tableName: '',
  mapFields: []
})
const options = ref([
  {
    label: '选项',
    value: 'code1'
  }
])
const businessSceneList = ref([]);
const metadataLibrarys = ref([]);
const templateList = ref([]);
const tableList = ref([]);
const curSourceFields = ref([]); // 当前已选择的字段列表
const rules = reactive({
  configMethod: [
    { required: true, message: '请选择配置方式', trigger: 'blur' },
  ],
  businessId: [
    { required: true, message: '请选择业务场景', trigger: 'blur' },
  ],
  databaseType: [
    { required: true, message: '请选择要素库类型', trigger: 'blur' },
  ],
  templateId: [
    { required: true, message: '请选择模板名称', trigger: 'blur' },
  ],
  tableName: [
    { required: true, message: '请选择数据库表名', trigger: 'blur' },
  ],
})
// 配置方式切换
const configMethodChange = () => {
  formInfo.value.businessId = '';
  formInfo.value.databaseType = '';
  formInfo.value.tableName = '';
  formInfo.value.templateId = '';
  formInfo.value.mapFields = [];
  tableList.value = [];
  curSourceFields.value = [];
}
// 源表字段切换
const fieldChange = (val, index) => {
  curSourceFields.value = formInfo.value.mapFields.map(item => item.sourceField);
}
const businessSceneChange = (val) => {
  if (val) {
    metadataLibrarys.value = [];
    templateList.value = []; 
    tableList.value = [];
    formInfo.value.tableName = '';
    formInfo.value.templateId = '';
    formInfo.value.databaseId = '';
    formInfo.value.databaseType = '';
    let businessItem = businessSceneList.value.find(item => item.id === val);
    formInfo.value.businessSceneName = businessItem?.name;
    getMetadataLibrary(val);
  }
}
const handleEvent = (type, data) => {
  formInfo.value.templateId = '';
  addVisible.value = false;
  if (formInfo.value.databaseType && formInfo.value.businessId) {
    let databaseId = metadataLibrarys.value.find(item => item.name === formInfo.value.databaseType).id;
    formInfo.value.databaseId = databaseId || '';
    getTemplateByCondition({
      businessId: formInfo.value.businessId,
      databaseType: formInfo.value.databaseType
    }).then(res => {
      templateList.value = res.rows;
    })  
  }
}
// 新增模板
const addTemplate = () => {
  addVisible.value = true;
}
// 要素库类型切换
const databaseChange = () => {
  formInfo.value.tableName = '';
  tableList.value = [];
  formInfo.value.templateId = '';
  if (formInfo.value.databaseType && formInfo.value.databaseType) {
    let databaseId = metadataLibrarys.value.find(item => item.name === formInfo.value.databaseType).id;
    formInfo.value.databaseId = databaseId || '';
    formInfo.value.configMethod == '1' ? getTemplateByCondition({
      businessId: formInfo.value.businessId,
      databaseType: formInfo.value.databaseType}).then(res => {
        templateList.value = res.rows;
      })  
    : getMetadataTableInfo({businessId: formInfo.value.businessId, databaseId }).then(res => {
      tableList.value = res.data;
    })
  }
}
// 要素库列表查询
const getTableOrTemplate = async () => {
  if (formInfo.value.databaseType && formInfo.value.businessId) {
    formInfo.value.configMethod == '1' ? await getTemplateByCondition({
      businessId: formInfo.value.businessId,
      databaseType: formInfo.value.databaseType}).then(res => {
        templateList.value = res.rows;
      })  
    : await getMetadataTableInfo({businessId: formInfo.value.businessId, databaseId: formInfo.value.databaseId }).then(res => {
      tableList.value = res.data;
    })
  }
}
const moduleChange = () => {
  if (formInfo.value.templateId) {
    formInfo.value.mapFields = [];
    let mapFieldsStr = templateList.value.find(item => item.id === formInfo.value.templateId).mapFields;
    formInfo.value.mapFields = JSON.parse(mapFieldsStr);
    formInfo.value.mapFields.forEach(item => {
      item.fieldType = item.targetFieldType;
    });
  }
}
const tableChange = () => {
  if (formInfo.value.tableName) {
    formInfo.value.mapFields = [];
    let table = tableList.value.find(item => item.tableName === formInfo.value.tableName);
    formInfo.value.mapFields = table?.mapFiledsList;
    formInfo.value.mapFields.forEach(item => {
      item.fieldType = item.targetFieldType;
    });
  }
}
// 获取业务场景列表
const getBusinessSceneList = async () => {
  await getBusinessSceneDefinitionList({pageNum: 1, pageSize: 999}).then(res => {
    businessSceneList.value = res.rows;
  })
}
// 获取要素库列表信息
const getMetadataLibrary = (sceneId) => {
  getMetadataDatabaseListByBusinessSceneCode({sceneId}).then(res => {
    metadataLibrarys.value = res.rows;
  })
}
const refreshSourceField = () => {
  curSourceFields.value = [];
  formInfo.value.mapFields.forEach(item => {
    item.sourceField = '';
  })
}
// watch(
//   props.sourceTable,
//   (newVal) => {
//     debugger
//     formInfo.value.mapFields.forEach(item => {
//       item.sourceField = '';
//     })  
//   }
// );
onMounted(async () => {
  // queryByCondition();
  await getBusinessSceneList();
  props.formInfo && (formInfo.value = props.formInfo);
  if (formInfo.value.businessId) {
    await getMetadataLibrary(formInfo.value.businessId);
    await getTableOrTemplate();
    await moduleChange();
    await tableChange();
  }
});
defineExpose({
  formInfo,
  formRef,
  refreshSourceField
});

</script>
<style scoped lang="scss">
:deep(.asterisk-left) {
  width: 100%;
}
</style>
